package com.easy.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.constant.RegularExpression;
import com.easy.common.core.domain.entity.User;
import com.easy.common.core.domain.model.RegisteredBody;
import com.easy.common.utils.uuid.SnowFlake;
import com.easy.user.mapper.MembershipMapper;
import com.easy.user.mapper.UserRegisteredMapper;
import com.easy.user.pojo.Membership;
import com.easy.user.service.IMembershipService;
import com.easy.user.service.IUserRegisteredService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserRegisteredServiceImpl extends ServiceImpl<UserRegisteredMapper, User> implements IUserRegisteredService {
    @Autowired
    private UserRegisteredMapper userRegisteredMapper;

    @Autowired
    private IMembershipService membershipService;

    /**
     * 用户注册
     *
     * @param registeredBody 注册机构
     * @return {@link String}
     */
    @Transactional
    @Override
    public boolean UserRegistered(RegisteredBody registeredBody) {

        SnowFlake snowFlake = new SnowFlake(11, 1);
        long id = snowFlake.nextId();

        User user = new User();
        Membership membership = new Membership();
        // id(雪花算法生成)
        user.setId(id);
        membership.setId(id);

        // 用户名（可不唯一）
        user.setUserName(registeredBody.getUsername());
        membership.setUserName(registeredBody.getUsername());

        // 密码
        user.setPassword(registeredBody.getPassword());

        // 手机号（邮箱）
        if (registeredBody.getUnique().matches(RegularExpression.PHONE_PATTERN)) {
            user.setPhone(registeredBody.getUnique());
        } else if (registeredBody.getUnique().matches(RegularExpression.MAIL_PATTERN)) {
            user.setEmail(registeredBody.getUnique());
        }

        // 申请为卖家
        user.setRemark(registeredBody.getType());

        // 会员信息存储
        int insert = userRegisteredMapper.insert(user);
        membershipService.addMembership(membership);

        return insert > 0;
    }
}
